#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
批量修复Django兼容性问题的脚本
"""
import os
import re
import glob

def fix_django_compatibility_file(file_path):
    """修复单个文件中的Django兼容性问题"""
    try:
        # 跳过不需要修复的文件
        if any(skip in file_path for skip in ['__pycache__', '.pyc', '.git', 'fix_']):
            return False
            
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        
        original_content = content
        
        # 1. 修复 SortedDict 导入问题 (Django 1.7+ 移除)
        content = re.sub(
            r'from django\.utils\.datastructures import SortedDict',
            'try:\n    from collections import OrderedDict as SortedDict\nexcept ImportError:\n    from django.utils.datastructures import SortedDict',
            content
        )
        
        # 2. 修复 patterns 导入问题 (Django 2.0+ 移除)
        content = re.sub(
            r'from django\.conf\.urls import patterns',
            '# patterns removed in Django 2.0+',
            content
        )
        
        # 3. 修复 patterns 使用
        content = re.sub(
            r'patterns\([\'"][^\'"]*[\'"],\s*',
            '[\n    ',
            content
        )
        
        # 修复 patterns 结尾
        content = re.sub(
            r'patterns\([\'"][^\'"]*[\'"],([^)]+)\)',
            r'[\1]',
            content
        )
        
        # 4. 修复 django.core.urlresolvers 导入
        content = re.sub(
            r'from django\.core\.urlresolvers import',
            'from django.urls import',
            content
        )
        
        # 5. 修复 url() 导入
        content = re.sub(
            r'from django\.conf\.urls import url',
            'from django.urls import path, re_path as url',
            content
        )
        
        # 6. 修复 include 导入
        content = re.sub(
            r'from django\.conf\.urls import include',
            'from django.urls import include',
            content
        )
        
        # 7. 修复 django.contrib.contenttypes.generic 导入
        content = re.sub(
            r'from django\.contrib\.contenttypes import generic',
            '''try:
    from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
    class generic:
        GenericForeignKey = GenericForeignKey
        GenericRelation = GenericRelation
except ImportError:
    from django.contrib.contenttypes import generic''',
            content
        )
        
        # 8. 修复 _meta.module_name 到 _meta.model_name
        content = re.sub(
            r'_meta\.module_name',
            '_meta.model_name',
            content
        )
        
        # 9. 修复 Django 3.0+ 的 force_unicode 问题
        content = re.sub(
            r'from django\.utils\.encoding import force_unicode',
            'from django.utils.encoding import force_str as force_unicode',
            content
        )
        
        # 10. 修复 Django 3.0+ 的 smart_unicode 问题
        content = re.sub(
            r'from django\.utils\.encoding import smart_unicode',
            'from django.utils.encoding import smart_str as smart_unicode',
            content
        )
        
        # 11. 修复 Django 4.0+ 的 force_text 问题
        content = re.sub(
            r'from django\.utils\.encoding import force_text',
            'from django.utils.encoding import force_str as force_text',
            content
        )
        
        # 12. 修复 iteritems() 为 items() (Python 3)
        content = re.sub(
            r'\.iteritems\(\)',
            '.items()',
            content
        )
        
        # 13. 修复 itervalues() 为 values() (Python 3)
        content = re.sub(
            r'\.itervalues\(\)',
            '.values()',
            content
        )
        
        # 14. 修复 iterkeys() 为 keys() (Python 3)
        content = re.sub(
            r'\.iterkeys\(\)',
            '.keys()',
            content
        )
        
        # 15. 修复 unicode() 为 str() (Python 3)
        content = re.sub(
            r'\bunicode\(',
            'str(',
            content
        )
        
        # 16. 修复 __unicode__ 为 __str__ (Python 3)
        content = re.sub(
            r'def __unicode__\(self\):',
            'def __str__(self):',
            content
        )
        
        # 17. 修复 Django 4.0+ 的 django.utils.translation
        content = re.sub(
            r'from django\.utils\.translation import ugettext as _',
            'from django.utils.translation import gettext as _',
            content
        )
        
        content = re.sub(
            r'from django\.utils\.translation import ugettext_noop',
            'from django.utils.translation import gettext_noop',
            content
        )
        
        # 只有在内容发生变化时才写入文件
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"✓ 修复完成: {file_path}")
            return True
        else:
            return False
            
    except Exception as e:
        print(f"✗ 修复失败 {file_path}: {e}")
        return False

def main():
    """主函数"""
    base_dir = os.path.dirname(os.path.abspath(__file__))
    
    print("开始批量修复Django兼容性问题...")
    print("=" * 50)
    
    # 获取所有Python文件
    python_files = []
    for root, dirs, files in os.walk(base_dir):
        # 跳过某些目录
        dirs[:] = [d for d in dirs if d not in ['__pycache__', '.git', 'static', 'media']]
        
        for file in files:
            if file.endswith('.py') and not file.startswith('fix_'):
                file_path = os.path.join(root, file)
                python_files.append(file_path)
    
    print(f"找到 {len(python_files)} 个Python文件")
    
    # 修复文件
    fixed_count = 0
    failed_count = 0
    
    for file_path in python_files:
        try:
            if fix_django_compatibility_file(file_path):
                fixed_count += 1
        except Exception as e:
            print(f"✗ 处理文件失败 {file_path}: {e}")
            failed_count += 1
    
    print("=" * 50)
    print(f"修复完成！")
    print(f"✓ 成功修复: {fixed_count} 个文件")
    print(f"✗ 失败: {failed_count} 个文件")
    print(f"总计处理: {len(python_files)} 个文件")

if __name__ == "__main__":
    main() 